<?php

class _F_EXTENSION_JQUERY_ extends _F_EXTENSION_ {
	
	public $prev_callback;	
	public $jquery_version = '1.7.1';
	public $jquery_ui_script = '/extensions/jquery/scripts/jquery-ui-1.8.18.min.js';
	
	public $_f_jquery_ = false;
	
	public function __construct() {
		f()->register_method('jquery',array($this,'jquery'));
		$this->prev_callback = f()->register_method(
			'post_process_callback',array($this,'_f_callback_'));
	}
	
	public function jquery($script = null) {
//		f()->script($this->jquery_script);
		$this->_f_jquery_ = true;
		if ($script == 'ui') f()->script($this->jquery_ui_script);
		else if (!empty($script)) f()->script("jQuery(function($) {\r\n$script\r\n});");
		return $this;
	}
	
	public function _f_callback_() {
		$buffer = '';
		if ($this->_f_jquery_) {
			$buffer .= '<script src="//ajax.googleapis.com/ajax/libs/jquery/'.
				$this->jquery_version."/jquery.min.js\"></script>\r\n".
				"<script>window.jQuery || document.write('<script src=\"".
				f()->url_base.'/extensions/jquery/scripts/jquery-'.
				$this->jquery_version.".min.js\"><\/script>')</script>\r\n";
		}
		f()->content = preg_replace('/<\/(body\s*)/im',"$buffer</$1",f()->content);
		if (isset($this->prev_callback)) call_user_func($this->prev_callback);
	}

}

new _F_EXTENSION_JQUERY_;
